package edu.controller;

import edu.service.UserRoleService;
import edu.service.UserService;
import edu.utils.PasswordUtils;
import edu.vo.Role;
import edu.vo.User;
import edu.vo.UserRole;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@Controller
@RequestMapping("/system")
public class SystemController {
    @Autowired
    private UserService userService;

    // 每页显示的记录数
    private static final int PAGE_SIZE = 10;
    @Autowired
    private UserRoleService userRoleService;

    // 更新用户锁定状态的接口
    @PostMapping("/updateLockStatus/{userId}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateLockStatus(
            @PathVariable Integer userId
    ) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取用户并切换锁定状态
            User user = userService.getUserById(userId).get();
            user.setLocked((user.getLocked() + 1) % 2);
            userService.updateUser(userId, user);

            result.put("success", true);
            result.put("message", "状态更新成功");
            result.put("locked", user.getLocked() == 1); // 返回新的锁定状态（true=已锁定）
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "状态更新失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    @GetMapping("/manage")
    public String userManage(
            Model model,
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") int page, // 当前页码，默认第1页
            @RequestParam(defaultValue = "id") String sortField, // 排序字段，默认按id排序
            @RequestParam(defaultValue = "asc") String sortDirection // 排序方向，默认升序
    ) {
        // 从Session中获取用户信息（假设登录时已存入）
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        if (loginUser == null) {
            // 用户未登录，重定向到登录页
            return "redirect:/edu/login";
        }

        // 将用户信息添加到模型中
        model.addAttribute("loginUser", loginUser);

        // 处理页码（页码从1开始，而PageRequest从0开始）
        int currentPage = page - 1; // 转换为0-based索引

        // 构建排序对象
        Sort sort = sortDirection.equalsIgnoreCase("desc")
                ? Sort.by(sortField).descending()
                : Sort.by(sortField).ascending();

        // 构建分页对象
        Pageable pageable = PageRequest.of(currentPage, PAGE_SIZE, sort);

        // 分页查询用户数据
        Page<User> userPage = userService.getAllUsers(pageable);

        // 计算分页信息并传递给页面
        model.addAttribute("users", userPage.getContent()); // 用户列表
        model.addAttribute("currentPage", page); // 当前页码（1-based）
        model.addAttribute("totalPages", userPage.getTotalPages()); // 总页数
        model.addAttribute("totalItems", userPage.getTotalElements()); // 总记录数
        model.addAttribute("hasPrevious", userPage.hasPrevious()); // 是否有上一页
        model.addAttribute("hasNext", userPage.hasNext()); // 是否有下一页
        model.addAttribute("sortField", sortField); // 当前排序字段
        model.addAttribute("sortDirection", sortDirection); // 当前排序方向

        return "system/userManage";
    }

    // 添加新用户
    @PostMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(@RequestBody Map<String, Object> userData) {
        Map<String, Object> result = new HashMap<>();
        try {
            String userName = (String) userData.get("userName");
            String password = (String) userData.get("password");
            String salt = (String) userData.get("salt");
            Integer locked = (Integer) userData.get("locked");
            List<String> roles = (List<String>) userData.get("roles");

            // 检查用户名是否已存在
            Optional<User> existingUser = userService.findByUserName(userName);
            if (existingUser.isPresent()) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                return result;
            }

            User newUser = new User();
            newUser.setUserName(userName);
            newUser.setSalt(salt);
            newUser.setPassword(PasswordUtils.hashPassword(password, salt));
            newUser.setLocked(locked);
            newUser.setCreatedAt(LocalDateTime.now());
            userService.saveUser(newUser);

            // 正确处理多角色分配
            if (roles != null && !roles.isEmpty()) {
                for (String role : roles) {
                    UserRole userRole = new UserRole();
                    userRole.setUser(newUser);

                    Role roleEntity = new Role();
                    if ("admin".equals(role)) {
                        roleEntity.setId(1);
                        roleEntity.setName("admin");
                    } else if ("teacher".equals(role)) {
                        roleEntity.setId(2);
                        roleEntity.setName("teacher");
                    } else if ("student".equals(role)) {
                        roleEntity.setId(3);
                        roleEntity.setName("student");
                    }

                    userRole.setRole(roleEntity);
                    userRoleService.saveUserRole(userRole);
                }
            }

            result.put("success", true);
            result.put("message", "用户添加成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // 删除用户
    @DeleteMapping("/users/{userId}")
    public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable Integer userId) {

        Map<String, Object> result = new HashMap<>();
        try {
            // 先删除用户角色关联
            userRoleService.deleteByUserId(userId);
            // 再删除用户
            userService.deleteUserById(userId);

            result.put("success", true);
            result.put("message", "用户删除成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "用户删除失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    @DeleteMapping("/deleteBatch")
    public ResponseEntity<Map<String, Object>> deleteBatch(@RequestBody List<Integer> userIds) {
        Map<String, Object> result = new HashMap<>();
        try {
            int deletedCount = 0;
            for (Integer userId : userIds) {
                try {
                    // 先删除用户角色关联
                    userRoleService.deleteByUserId(userId);
                    // 再删除用户
                    userService.deleteUserById(userId);
                    deletedCount++;
                } catch (Exception e) {
                    // 记录单个删除失败的情况，但继续处理其他用户
                    System.err.println("删除用户ID " + userId + " 失败: " + e.getMessage());
                }
            }

            result.put("success", true);
            result.put("message", "成功删除 " + deletedCount + " 个用户");
            result.put("deletedCount", deletedCount);
            result.put("totalCount", userIds.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除用户失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    // 获取用户信息接口
    @GetMapping("/getUser/{userId}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getUser(@PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取用户信息
            Optional<User> userOptional = userService.getUserById(userId);

            User user = userOptional.get();

            // 获取用户角色信息
            List<UserRole> userRoles = new ArrayList<>();
            List<UserRole> userRoleses = userRoleService.getAllUserRoles();
            userRoleses.forEach(userRole -> {
               if (userRole.getUser().getId().equals(userId)) {
                   userRoles.add(userRole);
               }
            });

            // 构建返回数据
            Map<String, Object> userData = new HashMap<>();
            userData.put("id", user.getId());
            userData.put("userName", user.getUserName());
            userData.put("locked", user.getLocked());
            userData.put("createdAt", user.getCreatedAt());

            // 构建角色列表
            List<Map<String, Object>> rolesList = userRoles.stream()
                    .map(ur -> {
                        Map<String, Object> roleMap = new HashMap<>();
                        roleMap.put("id", ur.getRole().getId());
                        roleMap.put("name", ur.getRole().getName());
                        return roleMap;
                    })
                    .toList();

            userData.put("userRoles", rolesList);

            result.put("success", true);
            result.put("data", userData);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取用户信息失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    // 更新用户信息接口
    @PutMapping("/updateUser")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateUser(@RequestBody Map<String, Object> userData) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId =  Integer.valueOf(String.valueOf(userData.get("id")));
            String userName = (String) userData.get("userName");
            String password = (String) userData.get("password");
            String salt = (String) userData.get("salt");
            Integer locked = (Integer) userData.get("locked");
            List<String> roles = (List<String>) userData.get("roles");

            Optional<User> userOptional = userService.getUserById(userId);

            User user = userOptional.get();

            // 更新用户名
            user.setUserName(userName);

            // 更新密码（如果提供了新密码）
            if (password != null && !password.isEmpty()) {
                user.setSalt(salt != null ? salt : user.getSalt()); // 使用新盐值或保持原有盐值
                user.setPassword(PasswordUtils.hashPassword(password, user.getSalt()));
            }

            // 更新锁定状态
            user.setLocked(locked);

            // 更新用户
            userService.updateUser(userId, user);

            // 更新用户角色关联
            // 先删除原有的角色关联
            userRoleService.deleteByUserId(userId);

            // 再添加新的角色关联
            if (roles != null && !roles.isEmpty()) {
                for (String role : roles) {
                    UserRole userRole = new UserRole();
                    userRole.setUser(user);

                    Role roleEntity = new Role();
                    if ("admin".equals(role)) {
                        roleEntity.setId(1);
                        roleEntity.setName("admin");
                    } else if ("teacher".equals(role)) {
                        roleEntity.setId(2);
                        roleEntity.setName("teacher");
                    } else if ("student".equals(role)) {
                        roleEntity.setId(3);
                        roleEntity.setName("student");
                    }

                    userRole.setRole(roleEntity);
                    userRoleService.saveUserRole(userRole);
                }
            }

            result.put("success", true);
            result.put("message", "用户信息更新成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "更新用户信息失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}
